package com.kuanter.kuanterauto.huiyuan;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.kuanter.adapter.Lv_kpxxAdapter;
import com.kuanter.adapter.Lv_xfjlAdapter;
import com.kuanter.kuanterauto.MainActivity;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.AccountList;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.entity.CardInfoList;
import com.kuanter.kuanterauto.entity.Consumption;
import com.kuanter.kuanterauto.entity.ConsumptionList;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.umeng.analytics.MobclickAgent;

/**
 * 会员界面
 * 
 * @author soup
 * 
 */
public class HuiYuanActivity extends BaseActivity_NoBar {

	private ViewPager mPager;// 页卡内容
	private List<View> listViews; // Tab页面列表
	// private ImageView cursor;// 动画图片
	private TextView t1, t2;// 页卡头标
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度

	private List<CardInfo> carinfos = null;// 客户卡片数据
	List<Consumption> consumptions = null;// 消费记录

	private ListView lv_kpxx = null;// 卡片详细listview
	private TextView tv_alljf = null;// 总积分
	private TextView tv_alljf2 = null;// 总积分
	private ImageView cursor;// 动画图片
	private Lv_kpxxAdapter kaxxAdapter = null;
	private int integral = 0;
	private int cardNum = 0;

	private ListView lv_xfjl = null;
	private Lv_xfjlAdapter xfjlAdapter = null;
	
	DataLoader dataLoader=null;
	
	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.huiyuan);
		dataLoader=new DataLoader(this);

//		if (getIntent().getExtras() != null) {
//			carinfos = (List<CardInfo>) getIntent().getExtras()
//					.getSerializable(CardInfoList.TAG);
//			consumptions = (List<Consumption>) getIntent().getExtras()
//					.getSerializable(ConsumptionList.TAG);
//			InitImageView();
//			InitTextView();
//			InitViewPager();
//		}else{
		if(CheckNetworkState()){
		showProgress("数据加载中...");
		InitImageView();
		InitTextView();
		InitViewPager();
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			params1.add(new BasicNameValuePair("cardInfo.userId", MainActivity.ID+""));
			dataLoader.DisplayData(MainConstants.HOST+ "cardInfo/query_card", params1, h_carinfos, "cardInfo/query_card",false);
			
			//消费记录
			List <NameValuePair> params2=new ArrayList<NameValuePair>();
			params2.add(new BasicNameValuePair("userConsumption.userId", MainActivity.ID+""));
			dataLoader.DisplayData(MainConstants.HOST+"consumption/query_consumption_record", params2, h_consumptions, "consumption/query_consumption_record",false);
			
		}
		
		
	}
	
	
	Handler h_carinfos=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HttpTask.RESULT_OK:
				CardInfoList cardInfoList = new CardInfoList(msg.getData().getString("result"));
				 carinfos = cardInfoList.getCarinfos();
				 if (carinfos != null) {
						cardNum = carinfos.size();
						for (int i = 0; i < carinfos.size(); i++) {
							if (carinfos.get(i).getAccoutlists() != null) {
								List<AccountList> accoutlists = carinfos.get(i)
										.getAccoutlists();
								for (int j = 0; j < accoutlists.size(); j++) {
									AccountList a = accoutlists.get(j);
									if (a.getAccountTypeName().equals("积分"))
										integral += Integer.parseInt(a.getBalance());
								}
							}
						}

						tv_alljf.setText("共计" + cardNum + "张卡");
						tv_alljf2.setText(integral + "积分");
						 if (carinfos != null&&carinfos.size()>0) {
								kaxxAdapter = new Lv_kpxxAdapter(HuiYuanActivity.this, carinfos,h_gs);
								lv_kpxx.setAdapter(kaxxAdapter);
								// lv_kpxx.setOnScrollListener(mScrollListener);
//								lv_kpxx.setVisibility(View.VISIBLE);
//								ListViewUtil.setListViewHeight(lv_kpxx);
							}
						 
					}
				 finishProgress();
				
				break;
			case HttpTask.RESULT_ERROR:
				showToast("服务器连接失败");
				finishProgress();
				break;
			}
		}
	};
	
	Handler h_consumptions=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HttpTask.RESULT_OK:
				ConsumptionList consumptionList=new ConsumptionList(msg.getData().getString("result"));
				 consumptions=consumptionList.getConsumptionList();
				 if (consumptions != null&&consumptions.size()>0) {
						xfjlAdapter = new Lv_xfjlAdapter(consumptions, HuiYuanActivity.this);
						lv_xfjl.setAdapter(xfjlAdapter);
					}
				 finishProgress();
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				break;
			}
		}
	};
	
	Handler h_gs=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HttpTask.RESULT_OK:
				showToast("挂失成功");
				break;
			case HttpTask.RESULT_ERROR:
				showToast("挂失失败");
				break;
			}
		}
	};

	/**
	 * 初始化头标
	 */
	private void InitTextView() {
		t1 = (TextView) findViewById(R.id.iv1);
		t2 = (TextView) findViewById(R.id.iv2);

		t1.setOnClickListener(new MyOnClickListener(0));
		t2.setOnClickListener(new MyOnClickListener(1));

	}

	/**
	 * 初始化ViewPager
	 */
	private void InitViewPager() {
		mPager = (ViewPager) findViewById(R.id.vPager);
		listViews = new ArrayList<View>();
		View v = getLayoutInflater().inflate(R.layout.lay1, null);
		View v2 = getLayoutInflater().inflate(R.layout.lay2, null);

		tv_alljf = (TextView) v.findViewById(R.id.tv_alljf);
		tv_alljf2 = (TextView) v.findViewById(R.id.tv_alljf2);
		lv_kpxx = (ListView) v.findViewById(R.id.lv_kpxx);

		lv_xfjl = (ListView) v2.findViewById(R.id.lv_xfjl);

		listViews.add(v);
		listViews.add(v2);
		mPager.setAdapter(new MyPagerAdapter(listViews));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
		
//		if (carinfos != null) {
//			cardNum = carinfos.size();
//			for (int i = 0; i < carinfos.size(); i++) {
//				if (carinfos.get(i).getAccoutlists() != null) {
//					List<AccountList> accoutlists = carinfos.get(i)
//							.getAccoutlists();
//					for (int j = 0; j < accoutlists.size(); j++) {
//						AccountList a = accoutlists.get(j);
//						if (a.getAccountTypeName().equals("积分"))
//							integral += Integer.parseInt(a.getBalance());
//					}
//				}
//			}
//
//			tv_alljf.setText("共计" + cardNum + "张卡 ———— " + integral + "积分");
//		}
//
//		if (carinfos != null&&carinfos.size()>0) {
//			kaxxAdapter = new Lv_kpxxAdapter(this, carinfos);
//			lv_kpxx.setAdapter(kaxxAdapter);
//			// lv_kpxx.setOnScrollListener(mScrollListener);
//		}
//
//		if (consumptions != null&&consumptions.size()>0) {
//			xfjlAdapter = new Lv_xfjlAdapter(consumptions, this);
//			lv_xfjl.setAdapter(xfjlAdapter);
//		}
		
		
	}
	
//	<ImageView
//    android:id="@+id/cursor"
//    android:layout_width="200dp"
//    android:layout_height="2dp"
//    android:layout_alignParentBottom="true"
//    android:background="#0f5ea0"
//    android:scaleType="matrix" />

	/**
	 * 初始化动画
	 */
	private void InitImageView() {
		 cursor = (ImageView) findViewById(R.id.cursor);
		 LayoutParams lp=new LayoutParams(this.getWindowManager().getDefaultDisplay().getWidth()/2, 3);
		 lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		 cursor.setLayoutParams(lp);
		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.a)
				.getWidth();// 获取图片宽度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		offset = (screenW / 2 - bmpW) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		 cursor.setImageMatrix(matrix);// 设置动画初始位置
	}
	
	
	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}
	
	

	/**
	 * ViewPager适配器
	 */
	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 2 + bmpW;
		int two = one * 2;

		
		
		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				System.out.println("one");
				t1.setTextColor(HuiYuanActivity.this.getResources().getColor(R.color.hyslColor));
				t2.setTextColor(HuiYuanActivity.this.getResources().getColor(R.color.hybgColor));
				if (currIndex == 1) {
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, 0, 0, 0);
				}
				break;
			case 1:
				System.out.println("two");
				t1.setTextColor(HuiYuanActivity.this.getResources().getColor(R.color.hybgColor));
				t2.setTextColor(HuiYuanActivity.this.getResources().getColor(R.color.hyslColor));
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, one, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, one, 0, 0);
				}
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			 cursor.startAnimation(animation);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	@Override
	protected void onDestroy() {
		// if (kaxxAdapter != null) {
		// ImageLoader imageLoader = kaxxAdapter.getImageLoader();
		// if (imageLoader != null) {
		// imageLoader.clearCache();
		// }
		// }
//		dataLoader.shutDown();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	OnScrollListener mScrollListener = new OnScrollListener() {
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				kaxxAdapter.setFlagBusy(true);
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				kaxxAdapter.setFlagBusy(false);
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				kaxxAdapter.setFlagBusy(false);
				break;
			default:
				break;
			}
			kaxxAdapter.notifyDataSetChanged();
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {

		}
	};
}
